package com.alogic.terminal.ssh.auth;

import ch.ethz.ssh2.Connection;
import com.alogic.terminal.ssh.Authenticator;
import com.anysoft.util.Configurable;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.code.Coder;
import com.anysoft.util.code.CoderFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 用户名和密码登录
 */
public class WithPassword implements Authenticator, Configurable {
    private static final Logger LOG = LoggerFactory.getLogger(WithPassword.class);
    private String username;
    private String password;
    private Coder coder = null;

    @Override
    public boolean authenticate(Connection conn) throws IOException {
        return conn.authenticateWithPassword(username,password);
    }

    @Override
    public void configure(Properties p) {
        username = PropertiesConstants.getString(p,"username","");
        password = PropertiesConstants.getString(p,"password","");

        if (StringUtils.isNotEmpty(password)) {
            try {
                Coder coder = CoderFactory.newCoder(PropertiesConstants.getString(p, "coder", "DES3"));
                password = coder.decode(password, username);
            } catch (Exception ex) {
                LOG.error("Can not find coder:" + coder);
            }
        }
    }
}
